import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Popconfirm, Radio, Select, Space } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { useModel } from 'umi';
import Config from './components/Config';
import Form from './components/Form';

import * as api from '@/services/ad';
import * as apiAreaFilter from '@/services/areaFilter';
import * as c from '@/services/consts';
import * as utils from '@/utils/utils';
import { PlusOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';

const List: React.FC = () => {
  const [formVisible, setFormVisible] = useState<boolean>(false);
  const [formConfigVisible, setFormConfigVisible] = useState<boolean>(false);
  const [current, setCurrent] = useState<API.Ad | undefined>(undefined);
  const [productId, setProductId] = useState<string | undefined>(undefined);
  const [policyAreaList, setPolicyAreaList] = useState<any[]>([]);

  const [filterAdPlatform, setFilterAdPlatform] = useState<string | undefined>(
    undefined,
  );
  const [filterAdType, setFilterAdType] = useState<string | undefined>(
    undefined,
  );
  const [filterPlatform, setFilterPlatform] = useState<string | undefined>(
    undefined,
  );
  const [filterChannel, setFilterChannel] = useState<string | undefined>(
    undefined,
  );
  const [filterPolicy, setFilterPolicy] = useState<string | undefined>(
    undefined,
  );

  const actionRef = useRef<ActionType>();

  const { hasRight } = useModel('useAuthModel');

  const { getProduct, getProductMenuItems, getAreaFilter } = useModel(
    'useGlobalModel',
    (model) => ({
      getProduct: model.getProduct,
      getProductMenuItems: model.getProductMenuItems,
      getAreaFilter: model.getAreaFilter,
    }),
  );

  const productMenuItems = getProductMenuItems(true);

  const handleFormSubmit = async (record: API.Ad) => {
    let result: API.Result;
    if (current) {
      result = await api.update({
        ...current,
        ...record,
      });
    } else {
      result = await api.add({ ...record });
    }

    if (result && result.success === true) {
      setCurrent(undefined);
      setFormVisible(false);
      actionRef.current?.reload();
    }
  };

  const handleRemove = async (id: number) => {
    const result = await api.remove({ key: id });
    if (result.success) {
      actionRef.current?.reload();
    }
  };

  const loadAreaFilters = async (params: { [key: string]: any }) => {
    const result = await apiAreaFilter.all(params);

    console.log('loadAreaFilters: ', params, result);

    if (result.success && result.data && result.data.length > 0) {
      let options: any[] = [];
      options.push(c.DefaultOptionAll);
      for (let item of result.data) {
        // let product = getProduct(item.productId);
        // let areas =
        //   item.areaGroup == c.AreaGroup.Foreign.value
        //     ? item.areas
        //     : item.areaGroup;

        options.push({
          //label: `(${product?.name})${item.name} [${areas}]`,
          label: `${item.name}`,
          value: item.id,
          disabled: !item.status,
        });
      }
      // console.log(options);

      setPolicyAreaList(options);
      //return Promise.resolve(options);
    } else {
      setPolicyAreaList([]);
    }
    // return Promise.resolve([]);
  };

  useEffect(() => {
    loadAreaFilters({ productIds: [productId] });
  }, [productId]);

  let columns: ProColumns<API.Ad>[] = [
    {
      title: '状态',
      align: 'center',
      width: 80,
      dataIndex: 'status',
      sorter: true,
      valueEnum: {
        true: { status: 'Success', text: '' },
        false: { status: 'Error', text: '' },
      },
    },
    {
      title: '产品',
      align: 'center',
      width: 100,
      dataIndex: 'productId',
      sorter: true,
      renderText: (_, record) => {
        if (record.productId) {
          const product = getProduct(record.productId);
          if (product) {
            return product.name;
          }
        }
        return '';
      },
    },
    {
      title: '广告平台',
      width: 120,
      align: 'center',
      dataIndex: 'adPlatform',
      sorter: true,
      renderText: (val) => {
        return `${c.getAdPlatformText(val)}`;
      },
    },
    {
      title: '广告类型',
      width: 120,
      align: 'center',
      dataIndex: 'adTypesString',
      sorter: true,
      renderText: (_, record) => {
        let text = '';
        for (let i = 0; i < record.adTypes?.length; i++) {
          if (text != '') {
            text += ',';
          }
          text += c.getAdTypeText(record.adTypes[i]);
        }
        return text;
      },
    },
    {
      title: '广告位置',
      width: 120,
      align: 'center',
      dataIndex: 'adSlot',
      sorter: true,
      renderText: (val) => {
        return `${c.getAdMobSlotText(val)}`;
      },
    },
    {
      title: '广告资源',
      dataIndex: 'refData',
      search: false,
      sorter: false,
      width: 360,
      render: (_, record) => {
        if (!record.refData) {
          return <></>;
        }

        let lines = [];
        for (let item of record.refData) {
          if (item.enabled) {
            lines.push(
              <>
                {item.refId}&nbsp;
                <br />
                {item.imageUrl !== undefined && item.imageUrl != '' && (
                  <>
                    <a
                      href={item.linkUrl != '' ? item.linkUrl : item.imageUrl}
                      title={item.linkUrl}
                      target="_blank"
                    >
                      {item.imageUrl}
                    </a>
                    <br />
                  </>
                )}
              </>,
            );
          }
        }
        return lines;

        // return record.refData.map((item) => {
        //   // <>
        //   //   {item.imageUrl}--{item.enabled}
        //   // </>;
        //   <>
        //     {item.adId}&nbsp;
        //     <br />
        //     {item.imageUrl !== undefined && item.imageUrl != '' && (
        //       <>
        //         <a
        //           href={item.linkUrl != '' ? item.linkUrl : item.imageUrl}
        //           title={item.linkUrl}
        //           target="_blank"
        //         >
        //           {item.imageUrl}
        //         </a>
        //         <br />
        //       </>
        //     )}
        //   </>;
        // });
      },
    },
    {
      title: '用户等级',
      width: 160,
      dataIndex: 'memberLevelsString',
      sorter: true,
      renderText: (_, record) => {
        let levelsText = '';
        for (let i = 0; i < record.memberLevels?.length; i++) {
          if (levelsText != '') {
            levelsText += ',';
          }
          levelsText += c.getMemberLevelText(record.memberLevels[i]);
        }
        return levelsText;
      },
    },
    {
      title: '平台',
      dataIndex: 'platformsString',
      sorter: true,
      renderText: (_, record) => {
        return record.platforms?.join(',');
      },
    },
    {
      title: '渠道',
      dataIndex: 'channelsString',
      sorter: true,
      renderText: (_, record) => {
        return record.channels?.join(',');
      },
    },
    {
      title: '版本条件',
      width: 200,
      sorter: false,
      render: (_, record) => {
        // if (
        //   record.policy?.platformAppVerCompares == null ||
        //   record.policy?.platformAppVerCompares.length < 1
        // ) {
        //   return <></>;
        // }

        let lines = [];

        if (
          record.policy != null &&
          record.policy.appVerCompare &&
          record.policy.appVerCompare != '' &&
          record.policy.appVer &&
          record.policy.appVer > 0
        ) {
          lines.push(
            <span>
              {record.policy.appVerCompare}
              {record.policy.appVer}

              <br />
            </span>,
          );
        }

        if (record.policy?.platformAppVerCompares) {
          for (let item of record.policy.platformAppVerCompares) {
            if (item.compareMode && item.compareMode != '') {
              lines.push(
                <span>
                  {item.platform}&nbsp;{item.compareMode}
                  {item.appVer}
                  <br />
                </span>,
              );
            }
          }
        }

        return lines;

        // if (
        //   record.policy != null &&
        //   record.policy.appVerCompare &&
        //   record.policy.appVerCompare != '' &&
        //   record.policy.appVer > 0
        // ) {
        //   return `${record.policy.appVerCompare}${record.policy.appVer}`;
        // }
        // return null;
      },
    },
    {
      title: '地区策略',
      dataIndex: '',
      sorter: false,
      render: (_, record) => {
        let policy = record.policy;
        if (
          policy &&
          policy.displayAreaFilterPolicy &&
          policy.displayAreaFilterPolicy != '' &&
          policy.displayAreaFilterPolicyAreaFilterIds &&
          policy.displayAreaFilterPolicyAreaFilterIds.length > 0
        ) {
          let text = '';
          if (
            policy.displayAreaFilterPolicy ==
            c.GroupDisplayAreaFilterPolicy.Display.value
          ) {
            text = '显示';
          } else if (
            policy.displayAreaFilterPolicy ==
            c.GroupDisplayAreaFilterPolicy.Hidden.value
          ) {
            text = '隐藏';
          }

          let fullAreas = [];

          for (
            let i = 0;
            i < policy.displayAreaFilterPolicyAreaFilterIds.length;
            i++
          ) {
            let id = policy.displayAreaFilterPolicyAreaFilterIds[i];

            let areaFilter = getAreaFilter(id);

            //console.log('policy.areaFilter: ', areaFilter);

            if (areaFilter != null) {
              let areas =
                areaFilter.areaGroup == c.AreaGroup.Foreign.value
                  ? areaFilter.areas
                  : areaFilter.areaGroup;

              fullAreas.push(areas);
            }
          }

          if (fullAreas.length > 0) {
            return `${text}:[${fullAreas.join(',')}]`;
          }
        }
        return null;
      },
    },
    {
      title: '排序',
      align: 'center',
      width: 80,
      dataIndex: 'sort',
      sorter: true,
    },
    {
      title: '更新时间',
      width: 160,
      align: 'center',
      dataIndex: 'updateTime',
      sorter: true,
      renderText: (val) => {
        return utils.formatUtcToLocal(val);
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      ellipsis: true,
    },
  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 140,
      render: (_, record) => {
        let cmps = [];
        if (hasRight('ad_update')) {
          cmps.push(
            <a
              key="edit"
              onClick={(e) => {
                setFormVisible(true);
                setCurrent(record);
              }}
            >
              编辑
            </a>,
          );
        }

        if (hasRight('ad_delete')) {
          cmps.push(
            <Popconfirm
              key="delete"
              title="确定要删除吗?"
              onConfirm={async () => {
                await handleRemove(record.id);
              }}
            >
              <a>删除</a>
            </Popconfirm>,
          );
        }

        return cmps;
      },
    },
  ]);

  return (
    <PageContainer>
      <ProTable
        rowKey="id"
        actionRef={actionRef}
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        search={false}
        pagination={false}
        toolbar={{
          menu: {
            type: 'tab',
            activeKey: productId,
            items: productMenuItems,
            onChange: (tabKey) => {
              //console.log('tabKey', tabKey);
              setProductId(tabKey as string);
            },
          },
        }}
        toolBarRender={() => {
          var toolbarDoms: any[] = [];
          toolbarDoms.push(
            <Space>
              <b>广告平台</b>
              <Radio.Group defaultValue="" buttonStyle="solid">
                <Radio.Button
                  value=""
                  onClick={() => {
                    setFilterAdPlatform(undefined);
                  }}
                >
                  全部
                </Radio.Button>
                {c.AdPlatformOptions.map((item) => (
                  <Radio.Button
                    value={item.value}
                    onClick={() => {
                      setFilterAdPlatform(item.value);
                    }}
                  >
                    {item.label}
                  </Radio.Button>
                ))}
              </Radio.Group>
            </Space>,
          );
          toolbarDoms.push(
            <Space>
              <b>广告类型</b>
              <Radio.Group defaultValue="" buttonStyle="solid">
                <Radio.Button
                  value=""
                  onClick={() => {
                    setFilterAdType(undefined);
                  }}
                >
                  全部
                </Radio.Button>
                {c.AdTypeOptions.map((item) => (
                  <Radio.Button
                    value={item.value}
                    onClick={() => {
                      setFilterAdType(item.value);
                    }}
                  >
                    {item.label}
                  </Radio.Button>
                ))}
              </Radio.Group>
            </Space>,
          );
          toolbarDoms.push(
            <Space>
              <b>平台</b>
              <Select
                style={{ width: 160 }}
                options={c.getObjectOptions(c.Platform, true)}
                onChange={(val) => {
                  setFilterPlatform(val);
                }}
              />
            </Space>,
          );
          toolbarDoms.push(
            <Space>
              <b>渠道</b>
              <Select
                style={{ width: 160 }}
                options={c.getObjectOptions(c.Channels, true)}
                onChange={(val) => {
                  setFilterChannel(val);
                }}
              />
            </Space>,
          );
          toolbarDoms.push(
            <Space>
              <b>地区策略</b>
              <Select
                style={{ width: 160 }}
                options={policyAreaList}
                onChange={(val) => {
                  setFilterPolicy(val);
                }}
              />
            </Space>,
          );

          if (hasRight('ad_create')) {
            toolbarDoms.push([
              <Button
                type="primary"
                key="config"
                onClick={() => {
                  setFormConfigVisible(true);
                }}
              >
                广告配置
              </Button>,
            ]);
            toolbarDoms.push([
              <Button
                type="primary"
                key="create"
                onClick={() => {
                  setFormVisible(true);
                }}
              >
                <PlusOutlined /> 新建
              </Button>,
            ]);
          }

          return (
            <Space
              style={{
                marginRight: '0px',
                width: 1600,
                justifyContent: 'right',
              }}
            >
              {toolbarDoms}
            </Space>
          );
        }}
        columns={columns}
        params={{
          productId:
            productId && productId !== c.DefaultOptionAll.key
              ? parseInt(productId)
              : undefined,
          adPlatform: filterAdPlatform,
          adType: filterAdType,
          platform: filterPlatform,
          channel: filterChannel,
          policy: filterPolicy,
        }}
        request={api.list}
      />
      <Form
        visible={formVisible}
        defaultProductId={
          productId && productId !== c.DefaultOptionAll.key
            ? parseInt(productId)
            : undefined
        }
        current={current}
        onSubmit={handleFormSubmit}
        onCancel={() => {
          setFormVisible(false);
          setCurrent(undefined);
        }}
      />
      <Config
        visible={formConfigVisible}
        defaultProductId={
          productId && productId !== c.DefaultOptionAll.key
            ? productId
            : undefined
        }
        onSubmit={() => {
          setFormConfigVisible(false);
        }}
        onCancel={() => {
          setFormConfigVisible(false);
        }}
      />
    </PageContainer>
  );
};

export default List;
